package com.bianmin.Controller;
import com.bianmin.Data.Result;
import com.bianmin.Mapper.UtilMapper;
import com.bianmin.coomen.AlyOssManager;
import com.bianmin.coomen.UploadManager;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.*;


@RestController
@RequestMapping("api/util")
public class UtilController {

    @Autowired
    private UtilMapper utilMapper;

    //上传图片
    @PostMapping("uploadImage")
    public Result<String> uploadImages(@RequestParam("file") MultipartFile file)  {
        AlyOssManager alyOssManager = new AlyOssManager();
        return alyOssManager.uploadFile(file);
    }

    //检查文字内容是否合法
    public boolean msgSecCheck(String str) {
        String accessToken = getAccessToken();
        String url = "https://api.weixin.qq.com/wxa/msg_sec_check?access_token=" + accessToken;

        Map<String,Object> map = new HashMap<>();
        map.put("content",str);

        String param = mapToJsonString(map);
        Map<String, Object> result = requestWeChatApi(url, "post", param);
        System.out.println(result);
        int errcode = ((Number) result.get("errcode")).intValue();
        return errcode == 0;
    }

    //图片检测开关
    @GetMapping("imageSecSwitch")
    public Result<Integer> imageSecSwitch() {
        Integer status = utilMapper.queryImageSecSwitchStatus();
        return Result.success(status);
    }


    //检测图片合法性
    @PostMapping("imageSec")
    public Result<Object> imageSecCheck(@RequestParam("file") MultipartFile file) throws IOException {

        if (file == null) {
            return Result.customError(1001,"文件不能为空");
        }

        String accessToken = getAccessToken();
        //微信开放接口链接
        String url = "https://api.weixin.qq.com/wxa/img_sec_check?access_token=" + accessToken;
        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的
        HttpClient httpclient = HttpClients.createDefault();
        //创建一个post请求
        HttpPost request = new HttpPost(url);
        //设置响应头   （ application/octet-stream：二进制流，不知道下载文件类型）
        request.addHeader("Content-Type", "application/octet-stream");
        //输入流,获取输入图片的输入流
        InputStream inputStream = file.getInputStream();
        try {
            //创建一个byte数组，和输入的文件输入流大小一样
            byte[] byt = new byte[inputStream.available()];
            //从输入流中读取全部，并将其存储在缓冲区数组byt 中。
            inputStream.read(byt);
            //定制提交内容
            request.setEntity(new ByteArrayEntity(byt, ContentType.create("image/jpg")));
            //由客户端执行(发送)请求,执行校验
            HttpResponse response = httpclient.execute(request);
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity, "UTF-8");// 转成string
            //打印校验结果
            System.out.println("result：" + result);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.success(false);
    }


    //获取access_token
    public String getAccessToken() {
        String APPID="wx5f32bbcfb7d7ad60";
        String APPSECRET="2357f855c2ff86f577d8875fad9cb613";
        String accessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" + "&appid=" + APPID + "&secret=" + APPSECRET;
        String accessToken = "";
        Map<String, Object> stringObjectMap = requestWeChatApi(accessTokenUrl, "GET", "");
        accessToken = stringObjectMap.get("access_token").toString();
        return accessToken;
    }

    //接口请求accessToken
    @GetMapping("getAccessToken")
    public Result<String> requestAccessToken() {
        return Result.success(getAccessToken());
    }


    //请求微信API
    public Map<String, Object> requestWeChatApi(String requestUrl, String method, String postParams) {
        try {
            URL url = new URL(requestUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            // 根据方法类型设置属性
            if ("POST".equalsIgnoreCase(method)) {
                conn.setRequestMethod("POST");
                // 设置请求头，假设我们发送的是表单数据
                conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; application/json;");
                conn.setDoOutput(true); // 需要输出

                // 写入参数
                try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
                    if (postParams != null) {
                        wr.write(postParams.getBytes(StandardCharsets.UTF_8));
                        wr.flush();
                    }
                }
            } else { // 对于其他请求方法，如GET
                conn.setRequestMethod(method);
            }

            int responseCode = conn.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();

                String keyValuePairs = response.toString();
                Gson gson = new Gson();
                JsonObject jsonObject = gson.fromJson(keyValuePairs, JsonObject.class);

                Type mapType = new TypeToken<Map<String, Object>>(){}.getType();
                Map<String, Object> map = gson.fromJson(jsonObject, mapType);
                return map;
            } else {
                System.out.println(method + " request not worked");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new HashMap<>();
    }

    //将字符串转换成json字符串
    public String mapToJsonString(Map<String,Object> map) {
        Gson gson = new Gson();
        return gson.toJson(map);
    }

    @GetMapping("goodsList")
    public  Result<Object> goodsList() {
        return Result.success(utilMapper.goodsList());
    }

}
